package com.etooling.framework.controller;

import com.etooling.framework.entity.Org;
import com.etooling.framework.repository.OrgRepository;
import com.etooling.framework.svo.AntdTreeVo;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.VoToPoUtil;
import com.etooling.framework.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@EnableAutoConfiguration
@RequestMapping(value = "/admin/org")
/**
 * @title: OrgController
 * @description: 机构管理
 * @author 周志荣
 * @date 2020/12/18 17:57
 */
public class OrgController {
    @Autowired
    OrgRepository orgRepository;


    @RequestMapping("/add")
    @ResponseBody
    /**
     　　* @description:  新增机构
     　　* @param [request, org, pid]
     　　* @return com.irobot.framework.svo.ReplyObj
     　　* @throws
     　　* @author 周志荣
     　　* @date 2020/12/18 18:13
     　　*/
    ReplyObj add(HttpServletRequest request,
                 Org org,
                 @RequestParam(defaultValue = "", required = false, value = "pid") String pid
    ) {
        String companyId = (String) WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
        org.setStatus("启用");
        org.setCompanyId(companyId);
        org.setParentId(pid);
        orgRepository.save(org);
        return WebUtils.flushObjSuccess(org);
    }

    @RequestMapping("/update")
    @ResponseBody
        /*
         * @description: 修改机构
         * @param [request, org, newOrgId]
         * @return com.irobot.framework.svo.ReplyObj
         * @throws
         * @author 周志荣
         * @date 2020/12/18 18:13
         */
    ReplyObj update(HttpServletRequest request,
                    Org vo,
                    @RequestParam(defaultValue = "", required = false, value = "newOrgId") String newOrgId
    ) {
        try {

            Org po = orgRepository.getOne(vo.getId());
            VoToPoUtil.copyProperties(po, vo,new String[]{"parentId","companyId"});
            orgRepository.save(po);
            return WebUtils.flushObjSuccess(po);
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }

    }

    @RequestMapping("/del")
    @ResponseBody
        /*
         * @description: 删除机构
         * @param [request, org, newOrgId]
         * @return com.irobot.framework.svo.ReplyObj
         * @throws
         * @author 周志荣
         * @date 2020/12/18 18:14
         */
    ReplyObj del(HttpServletRequest request,
                 @RequestParam(defaultValue = "", required = false, value = "id") String id
    ) {
        try {
            Org org = orgRepository.getOne(id);
            orgRepository.delete(org);
            return WebUtils.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }

    }

    @RequestMapping("/getOrgTree")
    @ResponseBody
        /*
         * @description: 获取树形结构
         * @param [request, orgId]
         * @return com.irobot.framework.svo.ReplyObj
         * @throws
         * @author 周志荣
         * @date 2020/12/18 21:51
         */
    ReplyObj getOrgTree(HttpServletRequest request,
                        @RequestParam(defaultValue = "", required = false, value = "orgId") String parentOrgId
    ) {
        try {

            String companyId = (String) WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
            String orgId= WebUtils.getSessionValue(request, WebUtils.LOGIN_ORG_ID_KEY);
            Org org = orgRepository.getOne(orgId);
            //拿出这个节点下的所有节点
            Map<String, List<Org>> allChildrenNodes = this.getAllChildrenNode(orgRepository, parentOrgId,companyId);
            //所有有子的点，用于展开
            List<String> havaChildItmes = new ArrayList<>();
            Map<String, Object> treeMap = this.getChildTreeNode(org, allChildrenNodes, havaChildItmes);
            org = (Org) treeMap.get("rootTreeNode");
            havaChildItmes = (List<String>) treeMap.get("havaChildItmes");
            List<Org> tree = new ArrayList<>();
            tree.add(org);
            HashMap<String, List> returnValues = new HashMap<>();
            returnValues.put("treeData", tree);
            returnValues.put("havaChildItmes", havaChildItmes);
            return WebUtils.flushSuccess(returnValues);
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }
    }

    /*
     * @description:
     * @param [orgRepository 这个是方便其他控制调用, rootId]
     * @return java.util.Map<java.lang.String,java.util.List<com.irobot.jjb.entity.Org>>
     * @throws
     * @author 周志荣
     * @date 2020/12/19 11:55
     */
    public Map<String, List<Org>> getAllChildrenNode(OrgRepository orgRepository, String rootId, String companyId) {
        Map<String, List<Org>> allNodeMap = new HashMap<String, List<Org>>();
        if (!WebUtils.checkStr(rootId)) {
            rootId = "root";
        }
        List<Org> allChildrenNode = orgRepository.getOrgChildrenByParentId(rootId,companyId);
        for (int i = 0; i < allChildrenNode.size(); i++) {
            Org node = allChildrenNode.get(i);
            if (node.getParentId() == null || "".equals(node.getParentId())) {
                node.setParentId(rootId);
            }
            if (!(node.getParentId().equals(rootId) && node.getId().equals(rootId))) {
                if (allNodeMap.get(node.getParentId()) == null) {
                    List<Org> subList = new ArrayList<Org>();
                    subList.add(node);
                    allNodeMap.put(node.getParentId(), subList);
                } else {
                    List<Org> subList = allNodeMap.get(node.getParentId());
                    subList.add(node);
                }
            }
        }
        return allNodeMap;
    }

    public Map<String, Object> getChildTreeNode(Org rootTreeNode, Map<String, List<Org>> allChildrenNodeList, List<String> havaChildItmes) throws Exception {
        HashMap treeMap = new HashMap();
        List<Org> treelist = new ArrayList<Org>();
        String rootId = rootTreeNode.getId();
        List<Org> list = allChildrenNodeList.get(rootId);
        if (list != null && list.size() > 0) {
            for (Org node : list) {
                treelist.add(node);
                getChildTreeNode(node, allChildrenNodeList, havaChildItmes);
            }
            rootTreeNode.setChildren(treelist);
            havaChildItmes.add(rootTreeNode.getId());
        }
        treeMap.put("rootTreeNode", rootTreeNode);
        treeMap.put("havaChildItmes", havaChildItmes);
        return treeMap;
    }

    @RequestMapping("/getAntdTree")
    @ResponseBody
    ReplyObj getAntdTree(HttpServletRequest request,
                         @RequestParam(defaultValue = "", required = false, value = "parentOrgId") String parentOrgId
    ) {
        try {
            //拿出这个节点下的所有节点
            String orgId= WebUtils.getSessionValue(request, WebUtils.LOGIN_ORG_ID_KEY);

            Org org = orgRepository.getOne(orgId);

            String companyId = (String) WebUtils.getSessionValue(request, WebUtils.LOGIN_COMPANY_ID_KEY);
            AntdTreeVo treeVo = new AntdTreeVo();
            treeVo.setKey(org.getId());
            treeVo.setTitle(org.getName());
            Map<String, List<Org>> allChildrenNodes = this.getAllChildrenNode(orgRepository, parentOrgId,companyId);

            List<String> havaChildItmes = new ArrayList<>();
            Map<String, Object> treeMap = this.getAntdTreeNode(treeVo, allChildrenNodes, havaChildItmes);
            List<AntdTreeVo> tree = new ArrayList<>();

            treeVo = (AntdTreeVo) treeMap.get("rootTreeNode");
            tree.add(treeVo);
            havaChildItmes = (List<String>) treeMap.get("havaChildItmes");
            HashMap<String, List> returnValues = new HashMap<>();
            returnValues.put("treeData", tree);
            returnValues.put("havaChildItmes", havaChildItmes);
            return WebUtils.flushSuccess(returnValues);
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }

    }

    public Map<String, Object> getAntdTreeNode(AntdTreeVo treeNode, Map<String, List<Org>> allNodeMap, List<String> havaChildItmes) throws Exception {
        List<Org> list = new ArrayList<Org>();
        List<AntdTreeVo> treelist = new ArrayList<AntdTreeVo>();
        HashMap treeMap = new HashMap();
        String rootId = treeNode.getKey();
        list = allNodeMap.get(rootId);
        if (list != null && list.size() > 0) {

            for (Org po : list) {
                AntdTreeVo node = new AntdTreeVo();
                node.setKey(po.getId());
                node.setTitle(po.getName());
                treelist.add(node);
                getAntdTreeNode(node, allNodeMap, havaChildItmes);
            }
            treeNode.setChildren(treelist);
            havaChildItmes.add(rootId);
        }
        treeMap.put("rootTreeNode", treeNode);
        treeMap.put("havaChildItmes", havaChildItmes);
        return treeMap;
    }

}
